﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using vroom.wcf.service;
using vroom.wcf.service.cache;
using System.Reflection;
using vroom.wcf.common;

namespace Service
{
	public class WindowsService : ServiceBase
	{
		#region Members
		
		public ServiceHost _serviceHost = null;
		private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

		Thread _cacheManagerThread;
		CacheManager _cacheManager = new CacheManager(); 

		#endregion
	
		public WindowsService()
		{
			ServiceName = "WCF Service";
		}

		public static void Main()
		{
			ServiceBase.Run(new WindowsService());
		}

		protected override void OnStart(string[] args)
		{
			if (_serviceHost != null)
			{
				_serviceHost.Close();
			}

			_serviceHost = new ServiceHost(typeof(PosService));
			_serviceHost.Open();

			//Start CacheManager
			try
			{
				_cacheManagerThread = new Thread(new ThreadStart(_cacheManager.Start));
				_cacheManagerThread.Start();
			}
			catch (ThreadStateException tse)
			{
				_log.Error("Error in starting CacheManager", tse);
			}
			catch (Exception e)
			{
				_log.Error("Error in CacheManager", e);
			}

			_log.Info("Starting service");
		}

		protected override void OnStop()
		{
			if (_serviceHost != null)
			{
				_serviceHost.Close();
				_serviceHost = null;

				//Close CacheManager
				_cacheManagerThread.Abort(Enums.ServiceState.Shutdown);
				_log.Info("Closing service");
			}
		}
	}
}
